﻿using System.Text;
using System.Data;
using System.Reflection;


namespace BST250301TestStand.Models.Helpers
{
    public class Log
    {
        #region //记录日志，多线程等待。

        public delegate void showLogMsgDelegate(string msg);
        public delegate void showDGVMsgDelegate(string datetime, string result, string fanctionName, bool ispass, string msg);
        public static event showDGVMsgDelegate ShowSendDGVMsgEnventHandle;
        static ReaderWriterLockSlim ErroLogWriteLock = new ReaderWriterLockSlim();
        static ReaderWriterLockSlim LiveLogWriteLock = new ReaderWriterLockSlim();
        static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();

        public static void ByTime(string logtxt)
        {
            Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}------Mssage:{logtxt}\r\n");

            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + $"\\Log\\");
            try
            {
                //System.IO.DirectoryInfo fileInfo = new DirectoryInfo(newPath);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                LogWriteLock.EnterWriteLock();
                string logName = filePath+DateTime.Today.ToLongDateString()+ "_Log.txt";
                StreamWriter sw = File.AppendText(logName);
                //if (logtxt.Contains("password") || logtxt.Contains("密码") || logtxt.Contains("Password") || logtxt.Contains("PASSWORD") || logtxt.Contains("PassWord"))// "含有密钥信息未能显示")
                //    logtxt = "含有密钥信息未能显示";

                sw.Write($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}------Mssage:{logtxt}\r\n");
                sw.Close();
                //Console.WriteLine($"{DateTime.Now.ToString()}------Mssage:{logtxt}");
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建日志错误！" + ex.Message);
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }
        public static void LiveByTime(string logtxt)
        {
            Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}------Mssage:{logtxt}\r\n");
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + $"\\Log\\");
            try
            {
                //System.IO.DirectoryInfo fileInfo = new DirectoryInfo(newPath);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                LiveLogWriteLock.EnterWriteLock();
                string logName = filePath + DateTime.Today.ToLongDateString() + "_Live.txt";
                StreamWriter sw = File.AppendText(logName);
                //if (logtxt.Contains("password") || logtxt.Contains("密码") || logtxt.Contains("Password") || logtxt.Contains("PASSWORD") || logtxt.Contains("PassWord"))// "含有密钥信息未能显示")
                //    logtxt = "含有密钥信息未能显示";
                sw.Write($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}------Mssage:{logtxt}\r\n");
                sw.Close();
                //Console.WriteLine($"{DateTime.Now.ToString()}------Mssage:{logtxt}");
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建日志错误！" + ex.Message);
            }
            finally
            {
                LiveLogWriteLock.ExitWriteLock();
            }
        }
        public static void ErrorByTime(string logtxt)
        {
            Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}------Error:{logtxt}\r\n");
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + $"\\Log\\");
            try
            {
                //System.IO.DirectoryInfo fileInfo = new DirectoryInfo(newPath);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                ErroLogWriteLock.EnterWriteLock();
                string logName = filePath + DateTime.Today.ToLongDateString() + "_Error.txt";
                StreamWriter sw = File.AppendText(logName);
                //if (logtxt.Contains("password") || logtxt.Contains("密码") || logtxt.Contains("Password") || logtxt.Contains("PASSWORD") || logtxt.Contains("PassWord"))// "含有密钥信息未能显示")
                //    logtxt = "含有密钥信息未能显示";
                sw.Write($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}------Error:{logtxt}\r\n");
                sw.Close();
                //Console.WriteLine($"{DateTime.Now.ToString()}------Mssage:{logtxt}");
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建日志错误！" + ex.Message);
            }
            finally
            {
                ErroLogWriteLock.ExitWriteLock();
            }
        }
        public static void SendResultKeXinByTime(string functionName, string bodytext, string starttime, string ts, string restext)
        {
            ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
            try
            {
                DateTime dt = DateTime.Now;
                string newPath = Path.Combine($"D:\\MESlog\\{functionName}\\{dt.ToString("yyyy")}\\{dt.ToString("MM")}\\{dt.ToString("dd")}");
                DirectoryInfo fileInfo = new DirectoryInfo(newPath);
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                LogWriteLock.EnterWriteLock();
                //StreamWriter sw = File.AppendText(newPath + "\\Send_Result_Log.csv");
                StreamWriter sw = File.AppendText(newPath + "\\流水号.csv");
                sw.Write($"{functionName},{bodytext},{starttime},{ts},{restext}\r\n");
                //请求接口	请求内容	开始调用时间	耗时	返回信息
                sw.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建日志错误！" + ex.Message);
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }
        public static void TraceCSVsave(string logtxt, string filePath,string fileName)
        {
            ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
            try
            {
                LogWriteLock.EnterWriteLock();
                DateTime dt = DateTime.Now;
                string fullpath = $"{filePath}\\{dt.Year}\\{dt.Month}\\{dt.Day}\\";
                SetLogPath(fullpath);
                string newPath = Path.Combine(fullpath, $"{fileName}.csv");

                UTF8Encoding utf8BOM = new UTF8Encoding(true);
                StreamWriter sw = new StreamWriter(newPath, true, utf8BOM);
                sw = File.AppendText(newPath);
                sw.Write($"{logtxt}\r\n");
                sw.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建CSV日志错误！" + ex.Message);
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }

        public static void AlarmCSVsave(DataSet ds, string filePath, string fileName)
        {
            ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
            LogWriteLock.EnterWriteLock();

            try
            {
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                    UTF8Encoding utf8 = new UTF8Encoding(true);
                    StreamWriter sw0 = new StreamWriter(Path.Combine(filePath, $"{fileName}.csv"), true, utf8);
                    //StreamWriter sw = File.AppendText(newPath);
                    {
                        sw0.Write($"ID,报警码,报警名称,报警描述,报警值,组件代码,位置,触发时间,恢复时间,报警原因,Note\r\n");
                    }
                    sw0.Close();
                }

                string newPath = Path.Combine(filePath, $"{fileName}.csv");
                UTF8Encoding utf8BOM = new UTF8Encoding(true);
                StreamWriter sw = new StreamWriter(newPath, true, utf8BOM);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    sw.Write($"{ds.Tables[0].Rows[i][0]?.ToString()},");
                    sw.Write($"{ds.Tables[0].Rows[i][1]?.ToString()},");
                    sw.Write($"{ds.Tables[0].Rows[i][2]?.ToString()},");
                    sw.Write($"{ds.Tables[0].Rows[i][3]?.ToString()},");
                    sw.Write($"{ds.Tables[0].Rows[i][4]?.ToString()},");
                    sw.Write($"{ds.Tables[0].Rows[i][5]?.ToString()},");
                    sw.Write($"{ds.Tables[0].Rows[i][6]?.ToString()},");

                    string activeTime = ds.Tables[0].Rows[i][7]?.ToString();
                    if (DateTime.Parse(activeTime) < DateTime.Parse("2000-1-1"))
                        sw.Write($",");
                    else
                        sw.Write($"{ds.Tables[0].Rows[i][7]?.ToString()},");
                    sw.Write($"{ds.Tables[0].Rows[i][8]?.ToString()},");
                    sw.Write($"{ds.Tables[0].Rows[i][9]?.ToString()}\r\n");
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建CSV日志错误！" + ex.Message);
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }
        public static void AlarmCSVsave<T>(T t, string filePath, string fileName)
        {
            ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
            LogWriteLock.EnterWriteLock();
            try
            {
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                    UTF8Encoding utf8 = new UTF8Encoding(true);
                    StreamWriter sw0 = new StreamWriter(Path.Combine(filePath, $"{fileName}.csv"), true, utf8);

                    Type myType = t.GetType();
                    PropertyInfo[] propertyInformation = myType.GetProperties();
                    for (int i = 0; i < propertyInformation.Length; i++)
                    {
                        sw0.Write($"{propertyInformation[i].Name},");
                    }
                    sw0.Write($"\r\n");

                    sw0.Close();
                }

                string newPath = Path.Combine(filePath, $"{fileName}.csv");
                UTF8Encoding utf8BOM = new UTF8Encoding(true);
                StreamWriter sw = new StreamWriter(newPath, true, utf8BOM);


                Type myTypeWrite = t.GetType();
                PropertyInfo[] propertyInformationmyTypeWrite = myTypeWrite.GetProperties();
                for (int i = 0; i < propertyInformationmyTypeWrite.Length; i++)
                {
                    object obj = propertyInformationmyTypeWrite[i].GetValue(t, null);
                    if (propertyInformationmyTypeWrite[i].Name.ToLower() =="activetime")
                    {
                        if (DateTime.Parse(propertyInformationmyTypeWrite[i].Name) < DateTime.Parse("2000-1-1"))
                            sw.Write($",");
                        else sw.Write($"{obj?.ToString()},");
                    }
                    else
                    {
                        sw.Write($"{obj?.ToString()},");
                    }
                }
                sw.Write($"\r\n");
                sw.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建CSV日志错误！" + ex.Message);
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }
        public static void LocalCSVsave(string logtxt, string filePath, string fileName)
        {
            ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();

            try
            {
                LogWriteLock.EnterWriteLock();
                DateTime dt = DateTime.Now;
                string fullpath = $"{filePath}\\{dt.Year}\\{dt.Month}\\{dt.Day}\\";
                SetLogPath(fullpath);
                string newPath = Path.Combine(fullpath, $"{fileName}.csv");
                UTF8Encoding utf8BOM = new UTF8Encoding(true);
                StreamWriter sw = new StreamWriter(newPath, true, utf8BOM);
                //StreamWriter sw = File.AppendText(newPath);
                sw.Write($"{DateTime.Now.ToString()}------:{logtxt}\r\n");
                sw.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建CSV日志错误！" + ex.Message);
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }
        public static bool SetLogPath(string fileFullPath)
        {
            try
            {
                if (!Directory.Exists(fileFullPath))
                {
                    Directory.CreateDirectory(fileFullPath);
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
           
        }
        public static void PLCByTime(string logtxt)
        {
            ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
            string newPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + $"\\Log_PLC2MES\\",
                DateTime.Today.ToLongDateString());
            try
            {
                DirectoryInfo fileInfo = new DirectoryInfo(newPath);
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                LogWriteLock.EnterWriteLock();
                string logName = newPath + "\\PLC_Log.txt";
                StreamWriter sw = File.AppendText(logName);
                sw.Write($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}------Mssage:{logtxt}\r\n");
                sw.Close();
                Console.WriteLine($"{DateTime.Now.ToString()}------Mssage:{logtxt}");
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建日志错误！" + ex.Message);
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }
        public static void SaveNVHSend(string logtxt)
        {
            string filePath = $"D:\\NVH\\";
            try
            {
                //System.IO.DirectoryInfo fileInfo = new DirectoryInfo(newPath);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string logName = filePath + "NVH-SN-TEST.txt";
                File.Delete(logName);
                StreamWriter sw = File.AppendText(logName);
                sw.Write(logtxt);
                sw.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建错误！" + ex.Message);
            }
            finally
            {
            }
        }
    }
}
#endregion